import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;




public class DataParser {

	public static void test() {
		try {
			ArrayList<Table> tables = parse(DataParser.class.getClassLoader().getResource("data.xml").openStream());
			
			for(Table itable : tables) {
				System.out.println(itable.getTableName());
				System.out.println(itable.getPrimaryKey());
				for (String s : itable.getEncryptColumn()) {
					System.out.println(s);
				}
			}
			
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static ArrayList<Table> parse(InputStream is) throws SAXException, IOException, ParserConfigurationException {
		if (is == null) return null;
		ArrayList<Table> data = new ArrayList<Table>();
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(is);
		NodeList nList = doc.getElementsByTagName("table");
		for(int i=0;i<nList.getLength();i++) {
			Node inode = nList.item(i);
			if (inode.getNodeType() != Node.ELEMENT_NODE) continue;
			Table itable = new Table();
			itable.setTableName(inode.getAttributes().getNamedItem("name").getNodeValue());
			NodeList childNodes = inode.getChildNodes();
			for (int j=0;j<childNodes.getLength();j++) {
				Node ichild = childNodes.item(j);
				if (ichild.getNodeType() != Node.ELEMENT_NODE) continue;
				ArrayList<String> encryptColumn = new ArrayList<String>();
				if (ichild.getNodeName().equals("primaryKey")) {
					itable.setPrimaryKey(ichild.getTextContent());
				} else {
					NodeList tmp = ichild.getChildNodes();
					
					for (int jj=0;jj<tmp.getLength();jj++) {
						Node enode = tmp.item(jj);
						if (enode.getNodeType() == Node.ELEMENT_NODE) {
							encryptColumn.add(enode.getTextContent());
						}
					}
				}
				itable.setEncryptColumn(encryptColumn);
			}
			data.add(itable);
		}
		return data;
	}
	
}
